package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.nio.channels.Channel;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author LX
 * @since 2022-06-17
 */
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {

    /**
     * 根据条件分页查询频道
     * @param dto
     * @return
     */
    @Override
    public PageResult<ChannelDto> findByPage(ChannelDto dto) {
//        设置分页条件
        Page<AdChannel> ipage = new Page<>(dto.getPage(),dto.getSize());
//        设置查询条件
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper<>();
        //            name 不为空，就查询
//        select * from ad_channel where name like '%?%'
//        if(StringUtils.isNotBlank(dto.getName())){
//            queryWrapper.like(AdChannel::getName,dto.getName());
//        }
        queryWrapper.like(StringUtils.isNotBlank(dto.getName()),AdChannel::getName,dto.getName());
//        分页查询
        IPage<AdChannel> channelIPage = page(ipage, queryWrapper);

        List<AdChannel> adChannelList = channelIPage.getRecords();

        if(CollectionUtils.isEmpty(adChannelList)){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        对象转换
        List<ChannelDto> channelDtos = BeanHelper.copyWithCollection(adChannelList, ChannelDto.class);
//        构造返回对象
        PageResult<ChannelDto> result = new PageResult<>(
                dto.getPage(),
                dto.getSize(),
                channelIPage.getTotal(),
                channelDtos);
        return result;
    }
}
